/**
 * @file 日志工具函数
 * @description 提供统一的日志记录功能
 * @date 2024-04-12
 */

// 导入环境配置
import { ENV } from '@/config/env';

// 日志级别枚举
export enum LogLevel {
  DEBUG = 0,
  INFO = 1,
  WARN = 2,
  ERROR = 3
}

// 环境信息
const isDevelopment = process.env.NODE_ENV === 'development';
const appVersion = import.meta.env.VITE_APP_VERSION || 'unknown';

// 从环境变量获取日志级别，默认开发环境为DEBUG，生产环境为INFO
const levelMap: Record<string, LogLevel> = {
  'debug': LogLevel.DEBUG,
  'info': LogLevel.INFO,
  'warn': LogLevel.WARN,
  'error': LogLevel.ERROR
};

const configLevel = ENV.LOG_LEVEL.toLowerCase();
const currentLevel = levelMap[configLevel] !== undefined 
  ? levelMap[configLevel] 
  : (isDevelopment ? LogLevel.DEBUG : LogLevel.INFO);

/**
 * 获取调用位置信息
 */
function getCallerInfo(): string {
  try {
    const err = new Error();
    const stack = err.stack?.split('\n') || [];
    
    // 查找第一个非logger.ts的调用行
    const callerLine = stack.find(line => 
      line.includes('at ') && !line.includes('logger.ts'));
    
    if (!callerLine) return 'unknown:0';
    
    // 提取文件名和行号
    const match = callerLine.match(/\((.+?):(\d+):\d+\)/) || 
                  callerLine.match(/at\s+(.+?):(\d+):\d+/);
    
    if (!match) return 'unknown:0';
    
    const filePath = match[1];
    const lineNumber = match[2];
    const fileName = filePath.split(/[\/\\]/).pop() || 'unknown';
    
    return `${fileName}:${lineNumber}`;
  } catch (e) {
    return 'unknown:0';
  }
}

/**
 * 创建日志输出
 */
function createLog(level: string, message: string, ...args: any[]): void {
  if ((levelMap[level.toLowerCase()] || 0) < currentLevel) return;

  const timestamp = new Date().toISOString();
  const location = getCallerInfo();
  const processedArgs = args.map(arg => arg instanceof Error ? {
    message: arg.message,
    name: arg.name,
    stack: arg.stack
  } : arg);

  // 控制台输出
  console[level.toLowerCase() as 'debug' | 'info' | 'warn' | 'error'](
    `[${timestamp}] [${level}] [${location}] ${message}`, 
    ...processedArgs
  );

  // 这里可以添加日志持久化逻辑
  // 例如发送到服务器或存储到本地
}

/**
 * 导出日志对象
 */
export const logger = {
  debug: (message: string, ...args: any[]) => createLog('DEBUG', message, ...args),
  info: (message: string, ...args: any[]) => createLog('INFO', message, ...args),
  warn: (message: string, ...args: any[]) => createLog('WARN', message, ...args),
  error: (message: string, ...args: any[]) => createLog('ERROR', message, ...args),
  // 暴露日志级别给外部使用
  level: {
    current: currentLevel,
    DEBUG: LogLevel.DEBUG,
    INFO: LogLevel.INFO,
    WARN: LogLevel.WARN,
    ERROR: LogLevel.ERROR
  }
}; 